﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Net;
using System.Web;

namespace RuleCode.Common
{
    public class Util
    {
        /// <summary>
        /// 验证是否通过   设置访问权限
        /// </summary>
        /// <returns></returns>
        public static bool ValidatePermission()
        {
            //设置访问权限     

            if (HttpContext.Current != null && HttpContext.Current.Request != null && (HttpContext.Current.Request.Url.Host != "localhost" && HttpContext.Current.Request.Url.Host != "book.cangbaowang.net"))
            {
                HttpContext.Current.Response.End();
                return false;
            }

            if(DateTime.Now .Year !=2010)
            {
                HttpContext.Current.Response.End();
                return false;
            }    
            return true;
        }

        #region 类型
        /// <summary>
        /// 获取 RuleCode 程序集的强命名信息
        /// </summary>
        public static string RuleCodeAssemblyInfo
        {
            get
            {
                //, Culture=neutral, PublicKeyToken=a847d883b3af710a
                return "RuleCode, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL";
            }
        }

        /// <summary>
        /// 获取 表的类型
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static System.Type GetTableType(string tableName)
        {
            return System.Type.GetType("RuleCode.Table." + tableName + "," + RuleCodeAssemblyInfo);
        }

        /// <summary>
        /// 获取字段类型
        /// </summary>
        /// <param name="fieldTypeName"></param>
        /// <returns></returns>
        public static System.Type GetFieldType(string fieldTypeName)
        {
            return System.Type.GetType("RuleCode.Table.TableField." + fieldTypeName + "," + RuleCodeAssemblyInfo);
        }

        /// <summary>
        /// 获取扩展类型的类型
        /// </summary>
        /// <param name="edtName"></param>
        /// <returns></returns>
        public static System.Type GetEdtType(string edtName)
        {
            return System.Type.GetType("RuleCode.ExtendType." + edtName + "," + RuleCodeAssemblyInfo);
        }

        /// <summary>
        /// 获取枚举的类型
        /// </summary>
        /// <param name="enumName"></param>
        /// <returns></returns>
        public static System.Type GetEnumType(string enumName)
        {
            return System.Type.GetType("RuleCode.Enmu." + enumName + "," + RuleCodeAssemblyInfo);
        }


        /// <summary>
        /// 根据字段类型把value值转换为字符串类型
        /// </summary>
        /// <param name="fieldType">字段类型</param>
        /// <param name="value">要转化的值</param>
        /// <returns>转化后的字符串的值</returns>
        public static string ObjectToString(System.Type fieldType, object value)
        {
            if (fieldType.BaseType == typeof(TInt) || fieldType == typeof(TInt))
                return TInt.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TInt64) || fieldType == typeof(TInt64))
                return TInt64.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TString) || fieldType == typeof(TString))
                return TString.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TFloat) || fieldType == typeof(TFloat))
                return TFloat.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TDouble) || fieldType == typeof(TDouble))
                return TDouble.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TDate) || fieldType == typeof(TDate))
                return TDate.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TTime) || fieldType == typeof(TTime))
                return TTime.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TContainer) || fieldType == typeof(TContainer))
                return TContainer.ObjectToString(value);
            else if (fieldType.BaseType == typeof(TEnum) || fieldType == typeof(TEnum))
                return TEnum.ObjectToString(value);
            else
                throw new InvalidCastException("没有与[" + fieldType.Name + "]相对应的类型可以进行转化");
        }
        /// <summary>
        /// 根据字段类型把字符串格式的值转化为值类型的值
        /// </summary>
        /// <param name="fieldType">将要转换的字段的类型</param>
        /// <param name="value">将要转化的字符串格式的值</param>
        /// <returns>转化后的值类型的值</returns>
        public static object StringToObject(System.Type fieldType, string value)
        {
            if (fieldType.BaseType == typeof(TInt) || fieldType == typeof(TInt))
                return TInt.StringToObject(value);
            else if (fieldType.BaseType == typeof(TInt64) || fieldType == typeof(TInt64))
                return TInt64.StringToObject(value);
            else if (fieldType.BaseType == typeof(TString) || fieldType == typeof(TString))
                return TString.StringToObject(value);
            else if (fieldType.BaseType == typeof(TFloat) || fieldType == typeof(TFloat))
                return TFloat.StringToObject(value);
            else if (fieldType.BaseType == typeof(TDouble) || fieldType == typeof(TDouble))
                return TDouble.StringToObject(value);
            else if (fieldType.BaseType == typeof(TDate) || fieldType == typeof(TDate))
                return TDate.StringToObject(value);
            else if (fieldType.BaseType == typeof(TTime) || fieldType == typeof(TTime))
                return TTime.StringToObject(value);
            else if (fieldType.BaseType == typeof(TContainer) || fieldType == typeof(TContainer))
                return TContainer.StringToObject(value);
            else if (fieldType.BaseType == typeof(TEnum) || fieldType == typeof(TEnum))
                return TEnum.StringToObject(value);
            else
                throw new InvalidCastException("没有与[" + fieldType.Name + "]相对应的类型可以进行转化");
        }
        #endregion

        #region Query相关
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fieldType">字段的基类</param>
        /// <returns></returns>
        public static Dictionary<string, RangeAction> GetActionDirectory(System.Type fieldType)
        {
            if (CaptionAttribute.Instance.NumeralTypes.Contains(fieldType))
                return NumericActionDirectory;
            if (CaptionAttribute.Instance.TStringTypes.Contains(fieldType))
                return StringActionDirectory;
            if (CaptionAttribute.Instance.EnumTypes.Contains(fieldType))
                return EnumActionDirectory;

            return AllRangeActionDirectory;
        }

        public static Dictionary<string, RangeAction> EnumActionDirectory
        {
            get
            {
                Dictionary<string, RangeAction> enumActionDirectory = new Dictionary<string, RangeAction>();
                enumActionDirectory.Add("=", RangeAction.EQUAL);
                enumActionDirectory.Add("!=", RangeAction.NOTEQUAL);
                return enumActionDirectory;

            }
        }

        public static Dictionary<string, RangeAction> AllRangeActionDirectory
        {
            get
            {
                Dictionary<string, RangeAction> allRangeActionDirectory = new Dictionary<string, RangeAction>();
                allRangeActionDirectory.Add("=", RangeAction.EQUAL);
                allRangeActionDirectory.Add("!=", RangeAction.NOTEQUAL);
                allRangeActionDirectory.Add(">", RangeAction.LARGER);
                allRangeActionDirectory.Add(">=", RangeAction.LARGEREQUAL);
                allRangeActionDirectory.Add("<", RangeAction.LITTLER);
                allRangeActionDirectory.Add("<=", RangeAction.LITTLEREQUAL);
                allRangeActionDirectory.Add("LIKE", RangeAction.LIKE);
                allRangeActionDirectory.Add("NOT LIKE", RangeAction.NOTLIKE);
                return allRangeActionDirectory;

            }
        }

        public static Dictionary<string, RangeAction> NumericActionDirectory
        {
            get
            {
                Dictionary<string, RangeAction> numericActionDirectory = new Dictionary<string, RangeAction>();
                numericActionDirectory.Add("=", RangeAction.EQUAL);
                numericActionDirectory.Add("!=", RangeAction.NOTEQUAL);
                numericActionDirectory.Add(">", RangeAction.LARGER);
                numericActionDirectory.Add(">=", RangeAction.LARGEREQUAL);
                numericActionDirectory.Add("<", RangeAction.LITTLER);
                numericActionDirectory.Add("<=", RangeAction.LITTLEREQUAL);
                return numericActionDirectory;
            }
        }

        public static Dictionary<string, RangeAction> StringActionDirectory
        {
            get
            {
                Dictionary<string, RangeAction> stringActionDirectory = new Dictionary<string, RangeAction>();
                stringActionDirectory.Add("=", RangeAction.EQUAL);
                stringActionDirectory.Add("!=", RangeAction.NOTEQUAL);
                stringActionDirectory.Add(">", RangeAction.LARGER);
                stringActionDirectory.Add(">=", RangeAction.LARGEREQUAL);
                stringActionDirectory.Add("<", RangeAction.LITTLER);
                stringActionDirectory.Add("<=", RangeAction.LITTLEREQUAL);
                stringActionDirectory.Add("LIKE", RangeAction.LIKE);
                stringActionDirectory.Add("NOT LIKE", RangeAction.NOTLIKE);
                return stringActionDirectory;
            }
        }

        public static string GetActionString(RangeAction rangeAction)
        {
            foreach (string key in AllRangeActionDirectory.Keys)
            {
                if (AllRangeActionDirectory[key] == rangeAction)
                    return key;
            }
            return "=";
        }

        #endregion

        #region 验证
        /// <summary>
        /// 验证 fieldType 是否为 tableType 中对应的表的字段的类型
        /// </summary>
        /// <param name="tableType"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public static bool Validate(System.Type tableType, System.Type fieldType)
        {
            bool result = true;
            result = result && tableType.IsSubclassOf(typeof(Table));
            result = result && fieldType.IsSubclassOf(typeof(TableFieldType));
            if (result == true)
            {
                TableFieldType field = Activator.CreateInstance(fieldType) as TableFieldType;
                if (field.BaseProperty != null)
                {
                    result = (tableType.GetProperty(field.BaseProperty.Name) != null);
                }
                else
                    result = false;
            }
            return result;
        }

        /// <summary>
        /// 验证 fieldName 是否为 tableName 中对应表的字段属性的名称
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public static bool Validate(string tableName, string fieldName)
        {
            bool result = true;
            System.Type tableType = GetTableType(tableName);

            result = result && (tableType != null);

            if (result == true)
            {
                PropertyInfo pInfo = tableType.GetProperty(fieldName);
                if (pInfo != null)
                    result = pInfo.PropertyType.IsSubclassOf(typeof(TableFieldType));
                else
                    result = false;
            }

            return result;
        }
        #endregion

        #region Payroll相关
        /// <summary>
        /// 计算 开始日期到结束日期之间的 有效工作日天数
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns></returns>
        public static int GetWorkDays(DateTime startDate, DateTime endDate)
        {
            DateTime referenceDate = new DateTime(1900, 1, 7);//参考日期，1900-1-7，星期日,startDate ,endDate 都应大于此数
            int validworkDays = 0;

            if (endDate > startDate)
            {
                int alldays = endDate.Subtract(startDate).Days + 1;
                int startWeekDay = (startDate.Subtract(referenceDate).Days % 7);
                int endWeekDay = (endDate.Subtract(referenceDate).Days % 7);
                startWeekDay = (startWeekDay > 0) ? (startWeekDay) : (7 + startWeekDay);
                endWeekDay = (endWeekDay > 0) ? (endWeekDay) : (7 + endWeekDay);


                if (alldays / 7 == 0)
                {
                    validworkDays = alldays - (((endWeekDay - 5) > 0) ? (endWeekDay - 5) : 0);
                    validworkDays = (validworkDays > 0) ? validworkDays : 0;
                }
                else
                {
                    if (alldays == 7)
                        validworkDays = 5;
                    else
                    {
                        //第一个半周和最后一个半周 的天数 大于一周的天数
                        if (8 - startWeekDay + endWeekDay > 7)
                        {
                            validworkDays = (alldays / 7 - 1) * 5 + (((6 - startWeekDay) > 0) ? (6 - startWeekDay) : 0) + endWeekDay;
                        }
                        //第一个半周和最后一个半周 的天数 等于一周的天数 alldays%7 ==0
                        else if (8 - startWeekDay + endWeekDay == 7)
                        {
                            validworkDays = (alldays / 7) * 5;
                        }
                        //第一个半周和最后一个半周 的天数 小于一周的天数
                        else
                        {
                            validworkDays = (alldays / 7) * 5 + (((6 - startWeekDay) > 0) ? (6 - startWeekDay) : 0) + endWeekDay;
                        }
                    }
                }
            }
            else if (endDate < startDate)
            {
                throw new InvalidOperationException("结束日期必须不小于开始日期！");
            }
            return validworkDays;

        }

        /// <summary>
        /// 获取月平均有效工作日
        /// 默认值 21.75
        /// </summary>
        [DefaultValue(21.75)]
        public static double WorkDaysEveryMonth = 21.75;

        /// <summary>
        /// 用于薪资计算时 平均工作日计算法 的参照的工作日天数
        /// </summary>
        public static double MiddleWorkDays = 15;

        /// <summary>
        /// 薪资计算类型
        /// 默认为 平均工作日 计算方法
        /// </summary>
        public static int PayrollCalculationType = 0;
        #endregion

        public static Int64 GetRecID()
        {
            Int64 recID = 0;
            DataSet dSet = SqlHelper.Instance.ExecuteQuery("GetRecID");
            if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
            {
                recID = Convert.ToInt64(dSet .Tables [0].Rows[0][0]);
            }
            return recID;
        }

    }
}
